/* 登录页思路分析
1.切换登录与注册盒子
2.登录功能
3.注册功能
*/
document.querySelector('.login a').addEventListener('click',function(){
    document.querySelector('.login').style.display='none'
    document.querySelector('.register').style.display='block'
})
document.querySelector('.register a').addEventListener('click',function(){
    document.querySelector('.register').style.display='none'
    document.querySelector('.login').style.display='block'
})

document.querySelector('.register .btn').addEventListener('click',function(e){
    e.preventDefault()
    let username = document.querySelector('.register [name="username"]').value
    let password = document.querySelector('.register [name="password"]').value
    if(username===''||password===''){
        return Toast.fail('输入不能为空')
    }
    if(/^\w{6,15}$/.test(username)==false||/^\w{6,15}$/.test(password)==false){
        return Toast.fail('输入不规范')
    }
    axios({
        url:'/api/register',
        method:'post',
        data: { username,password},
    }).then(res=>{
        console.log(res)
        if(res.data.code===0){
            Toast.success('注册成功')
            document.querySelector('.register a').click()
        }else(
            Toast.fail(res.data.message)
        )
    })
})

document.querySelector('.login .btn').addEventListener('click',function(e){
    e.preventDefault()
    let username = document.querySelector('.login [name="username"]').value
    let password = document.querySelector('.login [name="password"]').value
    axios({
        url:'/api/login',
        method:'post',
        data: { username,password},
    }).then(res=>{
        if(res.data.code===0){
            location.href='index.html'
            localStorage.setItem('token',res.data.token)
        }else(
            Toast.fail(res.data.message)
        )
        
    })
})
